package com.zzyl.framework.interceptor;

import cn.hutool.core.util.StrUtil;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.common.utils.UserThreadLocal;
import com.zzyl.framework.web.service.TokenService;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class MemberInterceptor implements HandlerInterceptor {

    @Autowired
    private TokenService tokenService;


    @Override  // 在请求处理之前进行调用（Controller方法调用之前）
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("authorization");
        if(StrUtil.isEmpty(token)){
            throw new BaseException("认证失败");
        }
        // 1、判断TOKEN字符串是否为空
        // 2、解析TOKEN字符串
        Claims claims = tokenService.parseToken(token);
        if(claims==null){
            throw new BaseException("认证失败");
        }

        // 3、获取UserId
        Long userId = Long.valueOf(claims.get("id").toString());
        // 4、放到ThreadLocal中
        UserThreadLocal.set(userId);
        return true;  //  true表示继续流程（如调用下一个拦截器或处理器）；false表示流程中断，不会调用后面的拦截器或处理器，返回给客户端响应
    }

    @Override // 请求处理之后进行调用，但是在视图被渲染之前（Controller方法调用之后）
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        UserThreadLocal.remove();
    }


}
